<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\MapNationalIndustrialParkModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\Common\CoordinateService;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportIndustrialPark extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wanggui:import-industrial-park';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入产业园信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址');

        if (!$url) {
            $url = 'https://file.51kuafu.com/c0/a8/3de3b7470b879a2db72d83022f6edfe21bfca63d9ead2283c47ad54f62c7.xlsx';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new SitePark(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class SitePark implements ToCollection
{

    private string $errMsg = '';

    private array $ratingArr = [];

    public function collection(Collection $collection)
    {
        // 校验列名信息
        $this->checkHeader($collection->first());

        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $num = 0;
        $collection->chunk(1000)->map(function ($chunk) use (&$num) {
            $chunk->map(function ($item, $row) use (&$num) {
                $row = $row + 1;

                if ($row == 1) {
                    return null;
                }
                // 常规内容校验
                list(
                    $name,
                    $province,
                    $city,
                    $district,
                    $lng,
                    $lat,
                    $grade,
                    ) = $item;

                $tempLatLng = CoordinateService::wgs84ToGcj02($lng, $lat);

                $industrialPark           = new MapNationalIndustrialParkModel();
                $industrialPark->name     = (string)$name;
                $industrialPark->province = (string)$province;
                $industrialPark->city     = (string)$city;
                $industrialPark->district = (string)$district;
                $industrialPark->lon      = $tempLatLng['lon'];
                $industrialPark->lat      = $tempLatLng['lat'];
                $industrialPark->grade    = ProgrammingEnum::GRADE_INVERSE_CODING_MAPPING[(string)$grade] ?? 2;
                $industrialPark->wgNumber = 'CYY33' . str_pad(($num + 1), 6, '0', STR_PAD_LEFT);
                $industrialPark->save();
                dump(++$num);
            })->filter();
        });
        dump($this->ratingArr);
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "产业园名称",
            "省份",
            "市",
            "区",
            "高德经度",
            "高德纬度",
            "产业园分级",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

}
